<template>
  <div class="setrole">
    <el-dialog
      title="给【系统管理员】分配权限"
      @close="cancle"
      :visible="roleShow"
    >
      <el-tree
        ref="tree"
        :data="treedata"
        :props="defaultprops"
        default-expand-all
        show-checkbox
        check-strictly
        node-key="id"
      ></el-tree>
      <div slot="footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="cancle">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAllPermissionApi } from '@/api/permission.js'
import { getRoleByIdApi, sysRoleAssignPremApi } from '../../../api/role'
export default {
  props: ['roleShow'],
  data () {
    return {
      // 树的数据源
      treedata: [],
      // 树的配置对象
      defaultprops: {
        label: 'name'
      },
      // 默认选中的权限 id 集合
      permIds: [],
      id: ''
    }
  },
  methods: {
    // 得到所有的权限数据
    async getpremisson () {
      const res = await getAllPermissionApi()
      this.treedata = this.turnData(res, '0')
    },
    // 将数据转为树状结构
    turnData (arr, str) {
      return arr.filter(item => {
        if (item.pid === str) {
          item.children = this.turnData(arr, item.id)
          return true
        }
      })
    },
    // 得到角色对应的权限列表
    async getRolePermission (id) {
      this.id = id
      console.log(this.id)
      const res = await getRoleByIdApi(id)
      this.permIds = res.permIds
      // ;将默认权限设置到 tree 中
      this.$refs.tree.setCheckedKeys(this.permIds)
    },
    // 点击取消
    cancle () {
      this.$emit('update:roleShow', false)
    },
    async submit () {
      // 得到修改后的权限
      this.permIds = this.$refs.tree.getCheckedKeys()
      try {
        // 提交数据
        await sysRoleAssignPremApi({
          id: this.id,
          permIds: this.permIds
        })
        // 关闭面板
        this.$emit('update:roleShow', false)
        // 提示成功
        this.$message.success('权限设置成功')
      } catch (err) {
        this.$message.error(err.message)
      }
    }
  },
  created () {
    this.getpremisson()
  }
}
</script>

<style></style>
